#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:最近一次订烟日期距今过久
code:LatestOrderDate_Check
tableName:
columnName:
groups:准入>烟商
dependencies:BTM
type:常用指标
dataSourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

def LatestOrderDate_Check():
    null_type_list = ['',None,'null','Null','/', ' ']
    indent_date = []
    try:
        BTM_ = BTM['data']
        if Formate(BTM_.get('bbd_dotime')) is not None:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
        else:
            ApplTime = datetime.datetime.now()
    except:
        return u'缺失值'
    try:
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
            and len(BTM_['indent']) >= 1:
            for i in BTM_['indent']:
                if i.has_key('indentDate') and i['indentDate'] not in null_type_list \
                        and Formate(i['indentDate']) is not None:
                    indent_date.append(Formate(i['indentDate']))
            last_indent = max(indent_date)  #上一次订烟日
            last_days = (ApplTime - datetime.datetime.strptime(last_indent,'%Y%m%d')).days

            return int(last_days)
        else:
            return u'缺失值'
    except:
        return u'缺失值'

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


result = LatestOrderDate_Check()